/*global chrome*/
chrome.runtime.onInstalled.addListener(function () {
    console.log('开始----')
    chrome.declarativeContent.onPageChanged.removeRules(undefined, function () {
        chrome.declarativeContent.onPageChanged.addRules([{
            // 运行插件运行的页面URL规则
            conditions: [
                new chrome.declarativeContent.PageStateMatcher({ pageUrl: {  }}),
            ],
            actions: [new chrome.declarativeContent.ShowPageAction()]
    }])
    })

})


var accessToken = ''

var loop = null
chrome.storage.sync.get(['accessToken'], (res)=>{
    // console.log(res.accessToken)
    if(res.accessToken != undefined){
        onhttp(res.accessToken)
    }
});

// 打开和关闭插件
chrome.runtime.onConnect.addListener((port)=>{
    console.log(port)
    if (port.name === "popup") {
        self.opens = true
        port.onDisconnect.addListener(()=>{
            console.log('port')
            if(accessToken != ''){
                onhttp(accessToken)
            }
            // alert('popup has been open')
        });
    }
});

// chrome.windows.getCurrent(function(wind) {
//     // alert(wind.id);
//     var maxWidth = window.screen.availWidth;
//     var maxHeight = window.screen.availHeight;
//     var updateInfo = {
//         left: 10, //change those to whatever you like 
//         top: 10,
//         width: maxWidth,
//         height: maxHeight
//     };
//     chrome.windows.update(wind.id, updateInfo);});

// console.log(chrome.runtime.getURL("target/notify.html"))
// chrome.windows.create({
//     url: chrome.runtime.getURL("target/index.html"),
//     type: "popup",
//     width:450,
//     height:700,
//     top:0,
//     left:screen.width - 400,
//   });


// chrome.browserAction.onClicked.addListener(function(tab) {
//   });

// chrome.tabs.create({'url': chrome.extension.getURL('target/notify.html'), type: "popup"});
// chrome.windows.create({'url': chrome.extension.getURL('target/notify.html'), 'selected': true});

// chrome.browserAction.onClicked.addListener(function(tab) {
//     console.log(tab)
//     // chrome.tabs.create({'url': chrome.extension.getURL('popup.html'), 'selected': true});
// });

// console.log(window.location.href)
// chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
//     console.log(tabs)
//     var currTab = tabs[0];
//     if (currTab) { // Sanity check
//       /* do stuff */
//     }
//   })
chrome.tabs.create({url: 'target/index.html#/login'});

// onhttp()
function onhttp(accessTokens){
    accessToken = accessTokens
    // accessToken = res.accessToken

    let url = 'https://matrix.moc.network/_matrix/client/r0/sync'
    fetch(url,{
    headers:{'Content-Type': 'application/json','authorization': 'Bearer '+accessTokens}
    }).then(response => { return response.json(); }).then(res =>{
        if(res.next_batch){
            onhttpsince(res.next_batch)
        }
    })
}

var timer = null;
function onhttpsince(since){
    console.log('拓展是否展开中',self.opens)
    if(self.opens == true){
        self.opens = false
        return
    }

    chrome.storage.sync.get(['accessToken'], (res)=>{
        console.log('old ---token',accessToken)
        
        if(accessToken == res.accessToken){
            console.log('----------==:',accessToken)
            // console.log('----------new:',res.accessToken)
            // console.log('执行onhttpsince:'+accessToken)
            let url = 'https://matrix.moc.network/_matrix/client/r0/sync?since='+since+'&timeout=30000&filter=1'
            // console.log(url)
            fetch(url,{
                headers:{'Content-Type': 'application/json','authorization': 'Bearer '+res.accessToken}
            }).then(response => { return response.json(); }).then(res =>{ 
                //使用节流，多次执行变为每隔3秒后执行一次 
                if(!timer){
                    timer = setTimeout(()=>{
                            onhttpsince(res.next_batch) 
                            timer = null;
                    },3000)
                }
                
                  
                if(res.rooms && res.rooms.join){
                    let obj = res.rooms.join
                    console.log('----since-res-----')
                    console.log(obj)
                    console.log('----since-res-----')
                    let keys =  Object.keys(obj)
                    // console.log(keys)
                    if( keys.length > 0 ){
                        for (const key in obj) {
                            // console.log(obj[key])
                            if(obj[key].timeline && obj[key].timeline.events && obj[key].timeline.events.length > 0){
                                let len = obj[key].timeline.events.length
                                let sender = obj[key].timeline.events[0].sender || ' '
                                sender = sender.split(":")[0]
                                var opt = {
                                        type: "list",
                                        title: sender,
                                        message: "消息",
                                        iconUrl: 'images/app.png',
                                        items: [{ title: "", message: 'webid有'+len+'条新消息'},]
                                    }
                                chrome.notifications.create('',opt,function(id){})
                            }
                        }
        
                    }
                }
            })
        }else{
            console.log('如果新token和旧token不相等，那就重新执行新token的函数')
            console.log('----------old:',accessToken)
            console.log('----------new:',res.accessToken)
            console.log('如果新token和旧token不相等，那就重新执行新token的函数')
            accessToken = res.accessToken
            // onhttp(res.accessToken)
        }
    
    });
}

// let val = self.accessToken
// console.log('打印 self.accessToken')
// console.log(val)
// Object.defineProperty(self,'accessToken',{
//     set(newVal){
//         console.log('检测到了新的数据变化',newVal)
//         // tips()
//     }
// })

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    // console.log('----------------------------')
    // 接受来自content-script的消息，requset里不允许传递function和file类型的参数
    chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) {  //chrome.tabs.query 同步
        const { contentRequest , config } = request
        // 接收来自content的api请求
        if (contentRequest === 'accessToken') {
            // console.log('--accessToken--')
            // console.log(accessToken)
            if(config.accessToken == accessToken){
                console.log('相等不用操作')
            }else{
                console.log('不相等操作')
                // accessToken = config.accessToken
                // 存储
                chrome.storage.sync.set({accessToken: config.accessToken}, ()=>{
                    console.log('accessToken is storage')
                });
                onhttp(config.accessToken)
            }
            // self.accessToken = config.accessToken
            // console.log(request)
            // localStorage.setItem('accessToken',contentRequest)
            // API请求成功的回调
            // sendResponse({
            //     result: 'suss',
            //     msg:'接收成功'
            // })
        }
    })
    return true
})
